<script>
// 动态加载组件
import widget from '@/mixins/widget'
import Widgets from '@/components/Widgets'

export default {
  name: 'Dynamic',
  mixins: [widget],

  data() {
    return {
      keyStatus: 'up'
    }
  },

  computed: {
    // 动态匹配组件主体
    dynamicComponent() {
      return Widgets[this.dataModel.type]['Main']
    },
    // 组件样式
    dynamicStyle() {
      if (this.flag === 'Generate') return 'dynamic'
      return ['dynamic', this.dataModel.selectStatus ? 'dynamic-active' : '']
    },
    // 动态返回传递的事件
    listeners() {
      // 按下Ctrl时，将传递绑定事件
      if (this.keyStatus === 'down' || this.flag === 'Generate') {
        return this.$listeners
      }
      return {}
    }
  },

  watch: {
    'dataModel.selectStatus': {
      deep: true,
      handler(newValue) {
        if (!newValue) this.keyStatus = 'up'
      }
    }
  },

  methods: {
    // 组件点击
    dynamicClick(e) {
      e.stopPropagation()

      this.selectWidget.selectStatus = false
      this.selectWidget = this.dataModel
      this.selectWidget.selectStatus = true
    },
    // 获取组件实例
    getInstance() {
      return this.$refs.dynamicComponent
    }
  },

  render() {
    // 监听按键
    const keyControl = {
      on: {
        keyup: e => {
          if (e.key === 'Control') {
            this.keyStatus = 'up'
          }
        },
        keydown: e => {
          if (e.key === 'Control') {
            this.keyStatus = 'down'
          }
        }
      }
    }

    // 动态组装组件
    let data = {
      ref: 'dynamicComponent',
      props: this.$props,
      attrs: this.$attrs,
      scopedSlots: this.$scopedSlots,
      on: this.listeners,
      style: this.dataModelBase.style
    }

    if (this.flag === 'Making') {
      data.nativeOn = {
        click: this.dynamicClick
      }
    }

    return (
      <div style="overflow:hidden">
        <div class={this.dynamicStyle} {...keyControl}>
          <div v-show={this.flag === 'Making'} class="dynamic-config__tips">
            {this.dataModel.name}
          </div>
          <this.dynamicComponent class="dynamic-main" {...data} />
        </div>
      </div>
    )
  }
}
</script>

<style lang="scss" scoped>
.dynamic {
  min-height: 20px;
  margin: 5px;
  border: 1px solid transparent;
  position: relative;

  &-config__tips {
    font-size: 12px;
    position: absolute;
    top: 1px;
    right: 1px;
    border-radius: 2px;
    z-index: 999;
    overflow: hidden;
    &::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: -1;
      background-color: #409eff;
      filter: blur(10px);
    }
  }

  &-main {
    min-height: 20px;
  }

  &-active {
    outline: 2px solid #409eff;
    border: 1px solid #409eff;
  }
}
</style>
